<?php
/**
 *类名：IMwalletPayTrade.php
 *功能  CP服务器端处理IM平台交易返回
 *版本：1.0
 *日期：2017-06-26
'说明：
 */

date_default_timezone_set('Asia/Shanghai');
//ini_set('error_reporting', 'E_ALL ^ E_NOTICE');
set_time_limit(0);
error_reporting(0);

include_once("./lib/mysql.class.php");
include_once("./lib/redis.class.php");
include_once("./lib/logger.php");
include_once("./lib/httpclient.php");
include_once("./connConfig.php");
include_once("./IMpay/config.php");


function recv_post_data() {
	$PostData = file_get_contents('php://input');
	Config::$loggerDebug->debug('IMwalletPayTrade',$PostData);
	return $PostData;
}

function record_post_data($PostData) {
    $date_dir = dirname(__FILE__).'/datalog/'.date('Y-m-d',time());
	if ( !is_dir( $date_dir ) ) {
        mkdir($date_dir, 0700);
    }
    file_put_contents($date_dir. '/' .rand(1000,9999). '-' .time(). '.txt', $PostData);
}

//数据公钥解签
function parse_post_data($PostData) {
	$publicKey = imconfig::$publicKey;
	imconfig::parseResp($PostData, $publicKey, $respJson);
	return $respJson;
}


//私钥解密
function private_decrypt($input) {
    $private_key = file_get_contents(__dir__ .'/IMpay/private_key.txt');	
    openssl_private_decrypt(base64_decode($input),$output,$private_key);  
    return $output;  
}  



function connect(&$redis, &$mysql) {
    $ret = $mysql->connect(Config::$mysql_config);
    if (!$ret) {
		Config::$loggerError->error('IMwalletPayTrade',"mysql connect error.");
        exit(0);
    }

    $ret = $redis->initCacheRedis();
    if (!$ret) {
        echo("cache redis connect error.\n");
		Config::$loggerError->error('IMwalletPayTrade',"cache redis connect error.");
        exit(0);
    }
}

function process($trade_no,&$payInfArr, &$redis, &$mysql, $attach, $third_trade_no) {
	if($attach==''){
		$row = $mysql->select('applypay','*',array('orderid' => $trade_no));
	}else{
		$attachArr = json_decode($attach,true);
		Config::$loggerDebug->debug('goodsid->',$attachArr['goodsid']);
		$row = $mysql->select('applypay','*',array('orderid' => $trade_no, 'goodsid'=>$attachArr['goodsid']));
	}
    
    if ( count($row) == 0) {
		Config::$loggerDebug->debug('IMwalletPayTrade',"have no order in applypay");
        exit(0);
    }
    
    $payInfArr = $row[0];
    $uid = (int)$payInfArr['uid'];
    $is_send = (int)$payInfArr['is_send'];
    $gid = (int)$payInfArr['goodsid'];
	$pay_type = (int)$payInfArr['pay_type'];
    //Config::$logger->info('IMwalletPayTrade',json_encode($payInfArr));
    //exit;
	
    //初始化用户redis
	$ret = $redis->initDataRedis($uid);
    if(!$ret) {
		Config::$loggerError->error('IMwalletPayTrade',"data redis connect error.");
        exit(0);
    }
   
    if ($is_send == 1) {
		Config::$loggerDebug->debug('IMwalletPayTrade',"repead order FAILURE.");
        exit("SUCCESS");
    }
	if(isset($attachArr['goodsid'])){
		$mysql->update('applypay',array('is_send' => 1,'third_party_order'=>$third_trade_no,'desc'=>'支付成功'),array('orderid' =>$trade_no,'goodsid'=>$attachArr['goodsid']));
	}else{
		$mysql->update('applypay',array('is_send' => 1,'third_party_order'=>$third_trade_no,'desc'=>'支付成功'),array('orderid' =>$trade_no));
	}
    

    //获取玩家信息
    $user = $redis->data_redis->hGetAll('hu:'.$uid);
	
	//获取商品信息
	$goods = $redis->cache_redis->hMGet('hg:'.$gid,array('money','type','propid','buy_money'));
	$num = $goods['money'];//产品数量
	$price = $goods['buy_money'] * 100;//产品价格
	
	
	
	
	//判断是否存在背包				
	$isExists = $redis->cache_redis->keys('hbackpack:'.$uid.":*");
	if(count($isExists) <= 0){
		//若不存在则添加背包并初始化
		$data = array('uid'=>$uid,'propid'=>(int)$good['propid'],'count'=>$num,'createtime'=>time(),'status'=>1);
		$redis->cache_redis->hMset('hbackpack:'.$uid.':'.(int)$goods['propid'],$data);
		//把商品变化写入表中
		$mysql->insert('goods_change_log',array('accid'=>$user['accid'],'uid'=>$uid,'third_party_order'=>$third_trade_no,'goodsid'=>$gid,
	                                            'type'=>$goods['type'],'pay_type'=>$pay_type,'amount'=>$num,'before_amount'=>0,'after_amount'=>$num,'create_date'=>time(),'price'=>$price));
		
	}else{
		//若存在则判断是否存在相同道具
		$isExistsProp = $redis->cache_redis->exists('hbackpack:'.$uid.':'.(int)$goods['propid']);
		//存在相同道具,则叠加
		if($isExistsProp){
			$row = $redis->cache_redis->hMget('hbackpack:'.$uid.':'.(int)$goods['propid'],array('propid','count'));
			if($row['propid']==1){//房卡
				$count = 0;
				$count = $row['count']+$num;
			    $redis->cache_redis->hMset('hbackpack:'.$uid.':'.(int)$goods['propid'],array('count'=>$count,'status'=>1));
			}
			//把商品变化写入表中
			$mysql->insert('goods_change_log',array('accid'=>$user['accid'],'uid'=>$uid,'third_party_order'=>$third_trade_no,'goodsid'=>$gid,
	                                                'type'=>$goods['type'],'pay_type'=>$pay_type,'amount'=>$num,'before_amount'=>$row['count'],'after_amount'=>$row['count']+$num,'create_date'=>time(),'price'=>$price));
		}else{
			//不存在相同道具,则添加记录
			$data = array('uid'=>$uid,'propid'=>(int)$goods['propid'],'count'=>$num,'createtime'=>time(),'status'=>1);
			$redis->cache_redis->hMset('hbackpack:'.$uid.':'.(int)$goods['propid'],$data);
			//把商品变化写入表中
			$mysql->insert('goods_change_log',array('accid'=>$user['accid'],'uid'=>$uid,'third_party_order'=>$third_trade_no,'goodsid'=>$gid,
	                                                'type'=>$goods['type'],'pay_type'=>$pay_type,'amount'=>$num,'before_amount'=>0,'after_amount'=>$row['count']+$num,'create_date'=>time(),'price'=>$price));
		}
		
	}
	
	//上报支付数据
	$redis->data_redis->select(3);
	$report_config = Config::$info_report;
	$pay_data = array('cid'=>$report_config['cid'],'user_id'=>$uid,'order_id'=>$third_trade_no,'pay_num'=>$price,'pay_time'=>time(),'imei'=>$user['device_num'],
					  'platform_type'=>$user['platform_type'],'channel'=>$user['channel'],'agent'=>$user['agent'],'user_name'=>$user['name'],'user_level'=>0,
					  'vip_level'=>0,'ip'=>$user['login_ip'],'ua'=>'','pay_channel'=>$pay_type);
	Config::$loggerDebug->debug('report',json_encode($pay_data));			  
	$redis->data_redis->rpush('pay_data',json_encode($pay_data));
}


/*
trade_no=63ccf1b239ac4f94898a8c56a474c7cd
&pay_type=1
&finished_datetime=2017-07-26 17:37:39
&created_datetime=2017-07-26 17:37:18
&notify_datetime=2017-07-26 17:46:40
&amount=3000
&out_trade_no=bcb00cfac523a8fd553b9766
&signature=zfMW7ujyczJQTKTAi3ueMj2rty1VXQnaJIi8u1hysc1uMrlwel3Rfef7ge7p+CBhO6K/49OkYyqiFX+v59nDe7ucoLjhPW7bOpYhJ5pybUbvV11vc139fxZZRrxHUDXh7eE+n2nqLMyank6RXoExjXJJmWmBuBBKNlrgIrsZbXA=
&trade_status=TRADE_SUCCESS&subject=长沙麻将
*/



function do_trade() {
    $PostData = recv_post_data();
    $PostData = urldecode($PostData);
	$respJson= parse_post_data($PostData);
	$trade_no = $respJson['out_trade_no'];//游戏订单号
	$third_trade_no = $respJson['trade_no'];//第三方订单号
	if(isset($respJson['attach'])){
		$attach = $respJson['attach'];
	}else{
		$attach = '';
	}
	Config::$loggerDebug->debug('IMwalletPayTrade->trade_no',$trade_no);
	Config::$loggerDebug->debug('IMwalletPayTrade->third_trade_no',$third_trade_no);
	$redis = new RedisDriver();
    $mysql = new MysqlDriver();
	connect($redis, $mysql);
	process($trade_no,$payInfArr,$redis, $mysql, $attach, $third_trade_no);
	$redis->deinitDataRedis();
    $redis->deinitCacheRedis();
    $mysql->close();
    exit("SUCCESS");
}

do_trade();

?>
